from flask import current_app, jsonify
from flask import render_template
from flask import request
from flask import session

from info import constants
from info.models import User, News, Category
from info.modules.index import blu
from info.response_code import RET


@blu.route('/')
def index():
    # 一、用户信息
    # 1.获取user_id
    user_id = session.get('user_id')
    # 2.根据session中的id查询数据库
    user = None
    if user_id:
        try:
            user = User.query.get(user_id)
        except Exception as e:
            current_app.logger.error(e)

    # 二、点击排行
    # 2.1查询数据库
    try:
        news_model_list = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno = RET.DBERR,errmsg = "数据查询失败")
    if not news_model_list:
        return jsonify(errno=RET.DBERR,errmsg = "没有数据")
    # 2.2模型列表    # 2.3模型转字典# 2.4拼接到data中
    news_dict_li = []
    for news in news_model_list:
        news_dict_li.append(news.to_dict())

    # 三、新闻分类
    # 3.1查询数据库  3.2循环模板得到数据字典  3.3拼接到data中
    try:
        categories = Category.query.all()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno = RET.DBERR,errmsg = "查询数据库失败")
    if not categories:
        return jsonify(errno = RET.DBERR,errmsg = "没有相关数据")
    category_dict_li = []
    for category in categories:
        category_dict_li.append(category.to_dict())

    # 获取数据库中信息
    data = {
        'user':user.to_dict() if user else None,
        'news_dict_li':news_dict_li,
        'category_dict_li':category_dict_li
    }

    # 4.返回数据给模板
    return render_template('news/index.html',data = data)


# 标题图标
@blu.route('/favicon.ico')
def favicon():
    return current_app.send_static_file('news/favicon.ico')


# 请求方式：GET
# url：/news_list
# 参数（选填）：category_id,page,pages
@blu.route('/news_list')
def get_news_list():
    # 获取参数
    cid = request.args.get('cid',1)
    page = request.args.get('page',1)
    pages = request.args.get('pages',10)
    # 校验参数(参数类型是数字）
    try:
        cid = int(cid)
        page = int(page)
        pages = int(pages)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno = RET.PARAMERR,errmsg ="请求参数不合法")

    # 查询数据库
    filter =[]
    if cid != 1:
        filter.append(News.category_id == cid)
    try:
        paginates = News.query.filter(*filter).order_by(News.create_time.desc()).paginate(page,pages,False)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno = RET.DBERR,errmsg ="查询数据库失败")

    news_model_list =paginates.items
    news_dict_li = []
    for news in news_model_list:
        news_dict_li.append(news.to_dict())
    # 需要的另外两个参数
    total_page = paginates.pages
    current_page = paginates.page
    # 返回数据
    data = {
        'total_page':total_page,
        'current_page':current_page,
        'news_dict_li':news_dict_li
    }
    return jsonify(errno = RET.OK,errmsg = "成功",data = data)